Repository navigation
feat: native BF16 GEMM for dense, batch and grouped entry points - #22
Merged
Merged
Conversation
Wanglongzhi2001
requested changes
Nov 3, 2026
YuhanXu
force-pushed
the
gemm_bf16
branch
2 times, most recently
from
November 4, 2026 15:27
7a87d3d to
8757ca2
Compare
Wanglongzhi2001
previously approved these changes
Nov 6, 2026
Collaborator
|
再补一个性能对比放到 |
Contributor
Author
已补充。rebase主线的时候出现了冲突,所以重新提了,麻烦再review一下 |
Collaborator
看着还是有冲突 |
Wanglongzhi2001
previously approved these changes
Nov 11, 2026
lizhenyun01
reviewed
Nov 12, 2026
Add a native BF16 MMA path on the self-developed SM100 mainloop: no scale
factors, a shape-aware tile ladder, tail-only stream-K and M-fast tile
traversal.
- gemm_tile / kernel_traits: KIsBF16 tile vocabulary, MMA atom width
decoupled from the cluster shape (KAtomCtas), epilogue warp-group
override, predicated N-tail store and right-sized TMEM allocation.
- bf16_cfgs.h: 35-tile dense catalog plus batch / contiguous / masked
catalogs with their dispatch selectors and per-tier entry guards.
- mainloop / epilogue: BF16 has no SF operands (default TMA atoms,
zero-sized SFA/SFB smem); fp32 partial deposit plus a stream-K reduce
kernel for split tails.
- tile_scheduler: M-fast traversal and tail-only stream-K decomposition.
- dense_gemm / batch_gemm / group_{masked,contiguous}_gemm: mode="bf16".
- python: sfa / sfb are Optional and become empty tensors for bf16.
- benchmark: bf16 dense / batch / grouped configs, a batch_gemm scenario,
CI configs and baselines; golden / deepgemm / flashinfer bf16 backends.
- tests: BF16 dense and batch / grouped accuracy tests.
Co-Authored-By: Claude Code <noreply@anthropic.com>
…placeholders Address review feedback on the BF16 GEMM commit: the four entry points (DenseGemm / BatchGemm / GroupContiguousGemm / GroupMaskedGemm) now take sfa/sfb as const std::optional<torch::Tensor>& — same convention as bias/alpha in these signatures — and the python wrappers no longer substitute torch.empty(0) placeholders before calling into the extension (pybind maps None to nullopt directly). Quantized branches (w8a8-mxfp8 / w4a4-*) gain an explicit has_value() check with a clear error message; the bf16 branch already ignored sfa/sfb and is unchanged. Verified: tests/test_gemm_bf16.py, tests/test_gemm_bf16_grouped.py all pass, quantized paths with real sfa/sfb unaffected. Co-Authored-By: Claude Code <noreply@anthropic.com>
Address review feedback on bf16_cfgs.h: - Drop every HALOPS_* tile-selection env knob (EnvIs / EnvNot0 / EnvIntOr / EnvInt64Or and ~30 switches) and fix each to the shipped default, so behaviour is unchanged; the cluster4 / stage-override / tile-k32 debug arms are gone with them. Also removes the HALOPS_FORCE_CFG hatch from dense_gemm.cu. - Rename the cryptic helpers: DeepProloguePays -> UseDeepPipeline, ThinMNoSwapOk -> SkipSwapForThinM, PacksTailTighter -> FillsLastWaveBetter, PreferFinePairN -> UseNarrowPairTile, PairDeepCtaCount -> Count128x64PairCtas. - Split the ~500-line SelectBF16Cfg ladder into per-region helpers (SelectLargeMTile / SelectMidMTile / SelectThinMTile / SelectSwapABTile, plus Pick128xNWidth / SelectPair256xNTile), preserving every decision. - Represent BF16 tiles as TileSpec tables next to kFp8Tiles/kFp4Tiles and derive the kernel configs through MakeTile (TileSpec gains epi_warp_groups / force_ntail); selectors and launch helpers move into gemm_dispatch.cuh; bf16_cfgs.h is deleted. The generic launcher now takes a tile-table policy, so FP8/FP4 use it unchanged. - Prune 10 BF16 tiles that only reachable through the removed env switches (2x2CTA cluster family, 128x32 K32/P4/P6, 64x64 P12/P14, 64x32 P14). - static_assert field locks replace the old GemmTile alias assertions. Verified: tests/test_gemm_bf16.py, test_gemm_bf16_grouped.py and the quantized dense/batch/contiguous/masked suites pass; ci dense_bf16 and batch_bf16 baselines pass within the 5% threshold (no dispatch drift). Co-Authored-By: Claude Code <noreply@anthropic.com>
Review feedback on 8757ca2: the new comments read like prose. Trim every comment that commit introduced — one or two lines per block, no bullet lists or rhetorical section headers, no restating what the code does. Technical facts (atom layouts, TMEM constraints, measured error numbers) are kept; wording only. Files: kernel_traits.cuh, tile_scheduler.cuh, mainloop_fwd.cuh, gemm_kernel.cuh, epilogue.cuh, stream_k_reduce.cuh, utils.cuh, gemm_utils.h, gemm_tile.cuh (parameter legend) and the two BF16 tests. Also drops one stale pointer in utils.cuh (BF16 tiles now live in gemm_tile.cuh) and a leftover reference to the deleted HALOPS_STREAMK switch. Verified: bf16 dense/batch/grouped tests and the quantized dense/batch/ contiguous/masked suites all pass (109 passed). Co-Authored-By: Claude Code <noreply@anthropic.com>
main PaddlePaddle#29 moved the batch D layout to [M, B * N] so the batched epilogue can share the dense one and feed the fused epilogue ops. That costs 9-11% on large-B / narrow-N / short-K shapes, where the kernel is write-bound and consecutive D rows sit B * N apart (4-8 MiB) instead of N. Keep the default layout and additionally accept the contiguous batch-major [B, M, N] output in mode="bf16" (the layout large-B callers want). Only d_ld and the per-batch row shift differ, both host-side parameters, so no extra kernel instantiation and no change to the default path. Quantized modes keep the 2D-only contract and its error messages. Measured (3 interleaved rounds, medians): restoring the contiguous layout recovers the whole gap -- [8192,64,512,64] 210.9 -> 185.6 us and [8192,64,256,64] 108.0 -> 99.1 us, while control shapes do not move. Also refreshes the two batch_bf16 CI baseline entries that the default layout affects, measured on the current machine (other seven entries and every dense_bf16 entry stay within the 5% threshold and are untouched). Co-Authored-By: Claude Code <noreply@anthropic.com>
The benchmark driver fed HALOps the default [M, B * N] output while every reference backend (bmm, flashinfer) writes [B, M, N]. Now that the bf16 batch epilogue also accepts the batch-major layout, drive all backends with the same tensor: fewer layouts to reason about, and the reported numbers match the layout large-B callers should use. Re-recorded all nine batch_bf16 CI entries from two runs (+-0.5% apart): no shape regressed, the two short-K shapes improved by 7.7% and 2.8% ([8192,64,512,64] 214.2 -> 198.0 us, [8192,64,256,64] 108.0 -> 105.0 us), and the remaining seven moved by <= 1.7%. The default [M, B * N] path keeps its own numbers in the previous commit; CI now guards this one. Co-Authored-By: Claude Code <noreply@anthropic.com>
Review feedback on the BF16 GEMM commit: the two dedicated test files were a separate suite with their own conventions. Move every case into the test file that already covers its entry point, so BF16 is just another mode there rather than a parallel suite. - test_dense_gemm.py: make_mode_inputs / make_empty_inputs gain a "bf16" branch; test_gemm_bf16 parametrizes the twelve shapes the old file ran (large-M, the N=1600 predicated tail at every M rung, large-M narrow N, mid-M, odd N, SwapAB, deep K); the bad-K case joins the shared unsupported-shape table. - test_batch_gemm.py: cases for the default [M, B * N] output and the batch-major [B, M, N] one, reusing assert_close_per_batch. - test_group_masked_gemm.py / test_group_contiguous_gemm.py: one BF16 case each, reusing the existing wrappers and comparison helpers. - gemm_utils.py: BF16_TOL next to the FP8/FP4 tolerances. - Delete tests/test_gemm_bf16.py and test_gemm_bf16_grouped.py: they set the seed and default device a second time, debug-printed, and hand-rolled the runtime-error assertion, all of which the shared fixtures and pytest.raises already cover. Also adds the missing test for the sfa/sfb-required check that the std::optional refactor introduced on the quantized branches. Verified: the four files pass (183 passed, 2 xfailed; the xfails are the pre-existing w4a8 masked sub-64 swap cases). Co-Authored-By: Claude Code <noreply@anthropic.com>
Review feedback on the BF16 GEMM commit: the BF16 windows had their own launch helpers and shape plumbing, so the four entry points looked unlike the quantized ones and the per-tile validation lived in a second place. - Dispatch: CandidateTilesFor<Kind, Mode> is the one place a kind maps to its candidate table (BF16 picks a table per mode, everything else keeps CandidateTiles<Kind>). LaunchCfg takes the pick from bf16::PickBf16Tile for BF16 and from the cost model otherwise, so dense, batch, contiguous and masked all read `LaunchCfg<KernelMode::X, MmaKind::BF16>(params, shape, stream)`. LaunchSelected and the four Launch* helpers are gone. - The tile divisibility check moves into LaunchTile, where it runs for every BF16 instantiation instead of only for the ones that went through a launch helper. - The rule ladder itself stays: it encodes measured bands and swapping it for the cost model would need a fresh sweep over every shape. - Drop ResolveSmCount (gemm_utils.h) and use the existing `sm_count > 0 ? sm_count : GetSmCount()` idiom the entry points already follow; drop CheckGemmTileShape, which had no callers. - Drop the comments above epilogue_bf16. Verified: build clean; dense/batch/grouped GEMM tests pass (183 passed, 2 xfailed); ci/test_benchmark.py passes all eight configs within the 5% threshold, so the FP8/FP4 dispatch and the BF16 numbers are unchanged. Co-Authored-By: Claude Code <noreply@anthropic.com>
With one tile table per mode, mapping a kind to its candidates needed its own adapter and the same tile was listed in up to four tables. - kBF16DenseTiles / kBF16ContiguousTiles / kBF16MaskedTiles / kBF16BatchTiles collapse into kBF16Tiles: 40 list entries become 28 distinct tiles. - The four id enums take their values from Bf16TileId(), a consteval lookup in that table, so an id cannot point at the wrong tile and a tile missing from the table fails to compile instead of selecting -1 at run time. - CandidateTiles<MmaKind::BF16> replaces the CandidateTilesFor adapter: every kind now resolves its candidates through the same single layer, and LaunchCfg / kTileLaunchers go back to CandidateTiles<Kind>. - The selection rules are untouched. PickBf16Tile still dispatches to the dense / contiguous / masked / batch ladders; the modes differ in how they pick, not in which table the ids index. Verified: build clean; the four GEMM test files pass (183 passed, 2 xfailed); ci/test_benchmark.py passes all eight configs within the 5% threshold. Co-Authored-By: Claude Code <noreply@anthropic.com>
…helpers First step of merging the BF16 epilogue into the shared one: epilogue_bf16 now reuses the helpers the quantized paths already have instead of keeping private copies. - D stores go through store_rows; the inline SwapAB b16 and predicated 256-bit copies are gone. Stores clip against the whole stacked D, not per batch: BF16 tiles never straddle a batch, and a per-batch bound kept the batch range live across the store loop (it spilled up to 104 bytes on the batch SwapAB tiles). - The overlap barrier uses overlap_arrive instead of a line-for-line copy. - d_shift computes the stacked-row to tile shift for both batch layouts ([M, B * N] and [B, M, N]); it replaces the BF16 path's own formula. - The EpiMIter loops always ran once (EpilogueTile and EpiComputeTile have the same M), so they are dropped and a static_assert pins the premise. Codegen against 7e512ad (cuobjdump --dump-resource-usage, 1238 gemm kernels): 1234 unchanged, including every quantized kernel; the two BF16 batch 128x256 kernels lose their 20 B spill, the two 128x32 SwapAB batch kernels go 160 -> 162 registers, no kernel spills. Verified: the four GEMM test files pass (183 passed, 2 xfailed); BF16 same-machine A/B against 7e512ad, two alternating rounds: dense_bf16 median -0.02% (-0.48%..+0.45%), batch_bf16 median -0.06% (-0.37%..+0.12%). ci/test_benchmark.py fails only dense_w8a8 8192x4096x4096 (+6.5..+7.6% over its 10-22 baseline), and 7e512ad fails it identically on this machine today, so that is drift of the stale baseline, not this change. Co-Authored-By: Claude Code <noreply@anthropic.com>
… loop epilogue_bf16 is gone: BF16 now takes the same sub-tile loop as the non-swap quantized path, and epilogue() dispatches between two families only (staged SwapAB quantized vs. the R2G loop). The BF16 differences are three compile-time switches in that loop: - Loader: BF16 reads TMEM through the partitioned tiled copy, which also covers the 16dp (64-row CTA) and 2SM "2x2" accumulator layouts; the quantized path keeps its raw unit load. - Store bound: BF16 clips against the whole stacked D (its tiles never straddle a batch), keeping the batch range out of the store loop. - Store target: a stream-K tail tile writes its fp32 partial; the BF16 N-tail joins the existing skip of sub-tiles past N. Overlap scheduling uses the shared run(): both BF16 overlap tiles overlap 16 columns, exactly one sub-tile, so the old wide-load branch read one sub-tile too. The traits that only fed that branch are removed (CopyOpT2R_Overlap, OverlapLoadTile, KOverlapLoadN, KWideTilesTotal, KSubTilesPerWG, KOverlapSubCount). d_shift reads batch_out_bmn for BF16 only, so the quantized shift is unchanged. Codegen against 7e512ad (1238 gemm kernels): every quantized kernel is unchanged. 24 BF16 kernels move; none uses LOCAL, but at the 168-register cap ptxas trades spills between tiles: dense 256x256 pair and contiguous 128x256 lose theirs (36/88 and 40/116 B), dense 128x256 and contiguous 256x256 pair gain 40/112 and 40/124 B. SASS shows what spills: the tile scheduler's start tile, grid stride, total tiles and warp_idx, which 7e512ad keeps in uniform registers, now sit in regular registers and are reloaded about five times per tile. Eight source-level variants of the new loop (in-place convert, bound selection, raw-register buffer, plain unit loop instead of run(), TMEM address, tile_rows, stream-K state) all leave it unchanged, and efa8a1b compiles the same tile without it, so it is ptxas's global uniform-register assignment, not one line of the loop. Verified: the four GEMM test files pass (183 passed, 2 xfailed), covering the BF16 overlap, N-tail, stream-K, SwapAB and batch-major cases. Same-machine A/B against 7e512ad, two alternating rounds: dense_bf16 median -0.27% (-1.50%..+0.30%; mid-M 256 and 1024 x4096x4096 -1.1%/-1.5%), batch_bf16 -0.03% (-0.26%..+0.17%), group_contiguous_bf16 +0.24% (-1.04%..+0.81%; the three M>=4096 4096-wide shapes on 256x256 pair +0.5..+0.8%), group_masked_bf16 -0.05% (-0.63%..+0.14%). Co-Authored-By: Claude Code <noreply@anthropic.com>
The quantized-output branch of the R2G sub-tile loop (UE8M0 scale per kGroup columns, e4m3 data through the SMEM stage and TMA, direct stores for rows above the box, then the row's scale word) moves out of the loop body into store_quant, defined next to the loop's other per-tile state. The loop now reads as load, transform, store, with one named store per output: store_rows (R2G), the stream-K partial store, and store_quant. The body moves verbatim; buf_i is declared ahead of the lambda, and expert_idx is passed in. Codegen against 032ac47: resource usage of all 1238 gemm kernels is unchanged (registers, stack, no spill). The instruction streams of 66 quantized kernels (128x64 / 128x128 / 128x256 / 256x64 / 256x128 / 256x256 with Quant, GateMulQuant, SituQuant, SigmoidGateMulQuant) differ only in the order of two adjacent independent zero moves (UMOV UR8, URZ / UMOV UR24, URZ) at four sites, checked on a single-tile build of 128x128 Quant: same instruction count, same registers, otherwise identical SASS. No other function changes. Verified: the four GEMM test files pass (183 passed, 2 xfailed). Co-Authored-By: Claude Code <noreply@anthropic.com>
…families The staged SwapAB loop and the R2G sub-tile loop each spelled out "this tile's expert alpha, or 1 without alpha"; both now call tile_alpha. With this the two families share every per-tile header helper (tile_rows, batch_col0, d_row, pair_rank, tile_alpha). The tile tail stays per family: the staged loop releases the accumulator stage mid-pipeline, the R2G loop after the last sub-tile load. Codegen against 3c1e1af: SASS of all 1374 functions is identical. Verified: the four GEMM test files pass (183 passed, 2 xfailed). Co-Authored-By: Claude Code <noreply@anthropic.com>
Wanglongzhi2001
previously approved these changes
Nov 27, 2026
lizhenyun01
reviewed
Dec 2, 2026
Remove debugging notes, stale performance claims, device-specific examples and explanations that repeat the code across the BF16 PR. Keep concise hardware, layout, synchronization and API contracts. Apply CI-pinned formatting and EOF fixes without changing executable tokens or configuration values. Keep performance changes parked. Co-Authored-By: Claude Code <noreply@anthropic.com>
lizhenyun01
approved these changes
Dec 3, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Add a native BF16 MMA path on the self-developed SM100 mainloop: no scale factors, a shape-aware tile ladder, tail-only stream-K and M-fast tile traversal.
Description / 变更说明
Accuracy impact / 精度影响
None
Performance impact / 性能影响
汇总 / Summary (geomean ratio, >1 = HALOps faster)
bmm(cuBLAS)deepgemmfi(cudnn)fi_cutlassDense
[128,128,4096]反超 ~18%deepgemm与fi两列几乎相同是预期的:dg 2.8.2 起 dense 的bf16_gemm_nt默认委托 cuBLASLt,fi 默认走 cudnn,二者最终都落到同一族nvjet_*JIT kernel——所以 dense 实际上是在跟 NVIDIA 的 JIT kernel 比Grouped (contiguous / masked)
deepgemmgeomean 1.10 / 1.05,小 shape 领先最多(1.2~1.4x)Batched
[M, B*N](默认)与[B, M, N](大 B 更快),benchmark 用后者与 bmm/flashinfer 对齐附:ratio 图
Checklist / 检查项
pytest tests/...), or skipped ones are listed / 已运行相关单元测试,或说明未运行的原因